package com.ojoin.trade.common.utils;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ojoin.trade.common.exception.BusinessException;

public class JavaMethodTimeOutUtils {
	final static ExecutorService exec = Executors.newFixedThreadPool(2);  
	private static Logger log = LoggerFactory
			.getLogger(JavaMethodTimeOutUtils.class);
	
	public static <T>  T excute(Callable<T> call) throws Exception{
		try {  
            Future<T> future = exec.submit(call);  
            T t= future.get(1000 * 10, TimeUnit.MILLISECONDS); //任务处理超时时间设为 1 秒  
            LogUtils.info(log, "方法执行完毕--〉 %s"+t);
            return t ;
        } catch (TimeoutException ex) {  
        	LogUtils.info(log, "方法超时--〉 %s"+ex);
        	 throw new BusinessException("方法超时") ;
        } catch (Exception e) {
        	LogUtils.error(log, e,"执行异常--> %s"+e );
        	throw e;
        }finally{
        	// 关闭线程池  
           // exec.shutdown(); 
        }  
        
	}
	
	
	
	
	public static void main(String[] args) {
		Callable<String> call = new Callable<String>() {  
			public String call() throws Exception {  
                //开始执行耗时操作  
                Thread.sleep(1000 * 5);  
                return "线程执行完成.";  
            }  
        };  
        
        
        try {
			JavaMethodTimeOutUtils.excute(call);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        
	}
	
}
